import { load, request } from '../common_node.js'

const source = {
  "id": "free_book_js/2",
  "name": "烟雨中文",
  "portalUrl": "https://www.yanyuzw.com",
  "searchBaseUrl": "https://www.yanyuzw.com",
  "bookBaseUrl": "https://www.yanyuzw.com",
  "active": true
};


async function searchBook(keyword, pageNum) {
  function getBoolList($) {
    const bookArr = [];
    const alistboxArr = $("ul.txt-list li");
    alistboxArr.each(function (index, elem) {
      if (index != 0) {
        let nameAndPath = $(this).find(".s2 a");
        bookArr.push({
          name: nameAndPath.html(),
          author: $(this).find(".s4").html(),
          path: nameAndPath.attr("href"),
          sourceId: source.id
        });
      }
    })
    return bookArr;
  }
  let url = source.searchBaseUrl + '/search?searchkey=' + encodeURIComponent(keyword);
  var html = await (await request(url)).text();
  var doc = load(html);
  var bookArr = getBoolList(doc);

  return {
    size: bookArr.length,
    pageNum: 1,
    pages: 1,
    sourceId: source.id,
    keyword: keyword,
    bookList: bookArr
  };
}

async function bookDetails(path) {
  var html = await (await request(source.bookBaseUrl + path)).text();
  let $ = load(html);

  return {
    name: $(".info .top h1").html(),
    author: $(".info .fix p").first().find('a').html(),
    path: path,
    sourceId: source.id,
    intro: $(".info .desc").html(),
    coverUrl: $(".imgbox img").attr("src"),
    type: $(".info .fix p").eq(1).html().replace('类&nbsp;&nbsp;别：', ''),
  };
}

async function bookCatalog(path) {
  async function fetchAndParseChapterInfo(pageUrl) {
    return request(pageUrl)
      .then((response) => response.text())
      .then((html) => {
        return getChapterInfo(load(html));
      });
  }

  function getChapterInfo($) {
    let catalog = [];
    let chapters = $(".section-list").eq(1).find('li');
    chapters.each(function (i, elem) {
      var item = $(this)
      catalog.push({
        index: null,
        title: item.find('a').html(),
        path: item.find('a').attr("href")
      });
    });
    return catalog;
  }
  var html = await (await request(source.bookBaseUrl + path)).text();
  var $ = load(html);
  const chapterPage = $('#indexselect option');

  let urlArr = [];
  chapterPage.each(function (i, elem) {
    if (i != 0)
      urlArr.push(source.bookBaseUrl + $(this).val())
  });
  //获取当前页面的章节
  let catalog = getChapterInfo($);

  //如果多页 多线程爬取
  if (urlArr.length > 0) {
    const promises = urlArr.map((pageUrl) => fetchAndParseChapterInfo(pageUrl));
    let chapterInfos = await Promise.all(promises)
    for (const iterator of chapterInfos) {
      catalog.push(...iterator);
    }
  }
  let index = 0;
  for (const iterator of catalog) {
    iterator.index = index++;
  }
  return catalog;
}

async function chapterContent(path) {
  var html = await (await request(source.bookBaseUrl + path)).text();
  const $ = load(html);
  //去除本章未完
  $("#content .btn-addbs").remove()
  let content = '';
  const pTags = $("#content p");
  pTags.each(function (index) {
    content += $(this).text();
    // 如果不是最后一个p标签，则添加换行符
    if (index !== pTags.length - 1) {
      content += '\n';
    }
  });
  let next = $("#next_url")
  if (next.text().includes("下一页")) {
    content += await chapterContent(next.attr("href"));
  }
  return content;
}

async function testSearchBook() {
  const result = await searchBook('穿越之大师兄', 1);
  console.log("搜索结果：", result);
  return result;
}

async function testBookDetails() {
  const result = await testSearchBook();
  const detatil = await bookDetails(result.bookList[0].path);
  console.log("书籍详情：", detatil);
  return detatil;
}

async function testBookCatalog() {
  const info = await testBookDetails();
  const result = await bookCatalog(info.path);
  console.log("书籍目录：", result);
  return result;
}

async function testChapterContent() {
  const catalog = await testBookCatalog();
  const result = await chapterContent(catalog[0].path);
  console.log("章节内容：\n", result);
}

await testChapterContent();
//debugger;

